﻿Imports OpenNETCF.Desktop.Communication
Imports System.IO
Imports ATS.UI.Process
Imports ATS.Business.Entities
Imports System.Security.Principal

Public Class ReaderWindow
    Public WithEvents oWindowList As OpenedWindowList = OpenedWindowList.GetList()
    Private WithEvents oWindow As OpenedWindowClass
    Dim FileFound As Integer
    Dim SearchCriteria As String = My.Settings.SearchCriteria
    Dim oRapi As RAPI
    Dim localLocation As String = My.Settings.localLocation
    Dim remoteLocation As String = My.Settings.remoteLocation
    Dim removeFilesonReader As Boolean = My.Settings.removeFilesonReader
    Dim recordCtr As String = 0
    Dim remotefileCount As New Integer
    Private _upc As SubmitterUserProcess = Nothing
    Dim scanHistory As RFIDScanHistory

#Region "Window Events"
    Public Sub New()
        ' This call is required by the designer.
        InitializeComponent()
        ' Add any initialization after the InitializeComponent() call.
        _upc = New SubmitterUserProcess()
    End Sub

    Private Sub ReaderWindow_Closing(sender As Object, e As System.ComponentModel.CancelEventArgs) Handles Me.Closing
        Dim ied As IEnumerable(Of OpenedWindowClass) = From d In oWindowList Where d.WindowID = Me.Name
        oWindowList.Remove(ied.First)
        If Application.Current.Windows.Count = 1 Then
            Application.Current.Windows(0).Activate()
        End If
    End Sub
#End Region

#Region "Support Procedures"
    Private Function IsDeviceConnected() As Boolean
        Try
            If oRapi.DevicePresent Then
                oRapi.Connect()
                If oRapi.Connected Then
                    Return True
                End If
            End If
        Catch ex As Exception
            If MsgBox("Cannot connect to the device. " & ex.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Device not found") = MsgBoxResult.Yes Then
                Return True
            End If
            Return False
        End Try
        If MsgBox("Cannot connect to the device." & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Device not found") = MsgBoxResult.Yes Then
            Return True
        End If
        Return False
    End Function

    Private Function FilesFoundOnDevice() As Boolean
        Dim files As Boolean = False
        Dim di As DirectoryInfo

        Try
            remotefileCount = 0
            If Not oRapi.EnumFiles(remoteLocation & My.Settings.readerFileExtension) Is Nothing Then
                remotefileCount = oRapi.EnumFiles(remoteLocation & My.Settings.readerFileExtension).Count
            End If
            If remotefileCount > 0 Then
                Try
                    di = New DirectoryInfo(localLocation)
                    If Not di.Exists Then
                        di.Create()
                    End If
                    For int As Integer = 0 To remotefileCount - 1
                        Try
                            oRapi.CopyFileFromDevice(localLocation & oRapi.EnumFiles(remoteLocation & My.Settings.readerFileExtension).Item(int).FileName, remoteLocation & oRapi.EnumFiles(remoteLocation & My.Settings.readerFileExtension).Item(int).FileName, True)
                            files = True
                        Catch RAPIerr As RAPIException
                            If MsgBox(RAPIerr.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                                files = True
                            End If
                        Catch ex As Exception
                            If MsgBox(ex.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                                files = True
                            End If
                        End Try
                    Next
                Catch ex As Exception
                    If MsgBox(ex.ToString & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                        files = True
                    End If
                End Try
            Else
                If MsgBox("No files found under reader directory " & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                    files = True
                End If
            End If
        Catch RAPIerr As RAPIException
            If MsgBox(RAPIerr.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed.") = MsgBoxResult.Yes Then
                files = True
            End If
        Catch ex As Exception
            If MsgBox("No files found at reader location: " & remoteLocation.ToString & ControlChars.Lf & "Continue to process files on local drive?", MsgBoxStyle.YesNo, "Copy File from Device failed") = MsgBoxResult.Yes Then
                files = True
            End If
        Finally
        End Try
        oRapi.Disconnect()
        Return files
    End Function

    Private Sub removeFilesFromDevice()
        Try
            oRapi.Connect()
            If oRapi.Connected Then
                Dim fileCount As Integer = oRapi.EnumFiles(remoteLocation & My.Settings.readerFileExtension).Count
                For int As Integer = 0 To fileCount - 1
                    Try
                        oRapi.DeleteDeviceFile(remoteLocation & oRapi.EnumFiles(remoteLocation & My.Settings.readerFileExtension).Item(0).FileName)
                    Catch RAPIerr As RAPIException
                        MsgBox(RAPIerr.ToString, MsgBoxStyle.Information, "Failed to remove files. Reconnect device and try again")
                    End Try
                Next
            End If
        Catch ex As Exception
            MsgBox(ex.ToString, MsgBoxStyle.Information, "Failed to remove files. Reconnect device and try again")
        End Try
        oRapi.Disconnect()
    End Sub

    Private Sub UpdateRFIDData()
        recordCtr = 0
        SearchCriteria = String.Empty

        Try
            Dim rowDelimiter As String = My.Settings.readerRowDelimiter
            If rowDelimiter.Trim.Length = 0 Then
                rowDelimiter = " "
            End If

            Dim path As String = localLocation
            Dim CriteriaPath, files, filename As String

            CriteriaPath = path.Substring(0, path.LastIndexOf("\"))

            If SearchCriteria.Length = 0 Then
                SearchCriteria = My.Settings.readerFileExtension
            Else
                SearchCriteria = path.Substring(path.LastIndexOf("\") + 1)
            End If

            Dim ListFiles() As String
            ListFiles = Directory.GetFiles(CriteriaPath, SearchCriteria)
            Array.Sort(ListFiles)

            For Each files In ListFiles 'Directory.GetFiles(CriteriaPath, SearchCriteria)
                filename = Mid(files, localLocation.Length + 1, files.Length - localLocation.Length + 1)
                Dim parser As New FileIO.TextFieldParser(files)
                'parser.TextFieldType = FileIO.FieldType.Delimited
                'parser.SetDelimiters(My.Settings.readerRowDelimeter)
                'While Not parser.EndOfData
                '    parser.ReadFields()
                'End While
                'parser.Close()
                'parser = New FileIO.TextFieldParser(files)
                parser.TextFieldType = FileIO.FieldType.Delimited
                parser.SetDelimiters(rowDelimiter)

                Dim rowFormat As String() = My.Settings.readerRowFormat.Split(";")
                Dim rowFieldCtr As Integer = 0
                For Each rowField In rowFormat
                    If rowField.ToString.ToUpper = "RFIDNUMBER" Then
                        Exit For
                    End If
                    rowFieldCtr += 1
                Next

                Dim currentRow() As String
                Dim fldCtr As Integer
                Dim rfidTempArray As New ArrayList
                Dim rfidNumberPrevious As String = Nothing
                Dim rfidScanDate As Date = CDate(Mid(filename, 1, 4) & "/" & Mid(filename, 5, 2) & "/" & Mid(filename, 7, 2))
                While Not parser.EndOfData
                    fldCtr = 0
                    Try
                        currentRow = parser.ReadFields()
                        Dim currentField As String
                        For Each currentField In currentRow
                            If fldCtr = rowFieldCtr Then
                                Dim rfidNumber As String = Mid(currentRow(rowFieldCtr), 1, My.Settings.readerRFIDNumberLength)

                                'skip if the same rfid number - might be scanned repeatedly
                                If rfidNumberPrevious <> rfidNumber Then
                                    rfidTempArray.Add(rfidNumber)
                                    rfidNumberPrevious = rfidNumber
                                End If

                                recordCtr += 1
                            End If
                            fldCtr += 1
                        Next
                    Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
                        MsgBox("Line " & ex.Message & _
                        "is not valid and will be skipped.")
                    End Try
                End While
                parser.Close()

                If Not rfidTempArray Is Nothing Then
                    rfidNumberPrevious = Nothing
                    rfidTempArray.Sort()
                    For Each itemArray In rfidTempArray
                        'skip if the same rfid number - might be scanned repeatedly
                        If rfidNumberPrevious <> itemArray.ToString Then
                            If _upc.ReadRFIDScanHistoryByRFIDNumber(itemArray.ToString, CDate(rfidScanDate)).Count = 0 Then
                                scanHistory = New RFIDScanHistory
                                scanHistory.RFIDNum = itemArray
                                scanHistory.DateScanned = rfidScanDate
                                'save scan details
                                '******************************************************************************************************************************************************
                                _upc.CreateRFIDScanHistory(scanHistory, My.Settings.readerCreateAssetData, WindowsIdentity.GetCurrent().Name) 'replace with ATS logged in USER
                            End If
                            rfidNumberPrevious = itemArray.ToString
                        End If
                    Next
                End If

                FileFound += 1
                If File.Exists(files) Then
                    File.Move(files, Mid(files, 1, files.Length - 3) & Format(Now(), "ddMMyyhhmmss"))
                Else
                    File.Move(files, Mid(files, 1, files.Length - 3) & "old")
                End If
            Next

            imgUpdateDatabaseError.Visibility = Windows.Visibility.Hidden
            imgUpdateDatabaseOk.Visibility = Windows.Visibility.Visible
            PBarimgUpdateDatabase.Visibility = Windows.Visibility.Hidden

            lblNumberofRecordsProcessed.Content = recordCtr
        Catch ex As Exception
            MsgBox("Please check format of reader files.")
            imgUpdateDatabaseError.Visibility = Windows.Visibility.Visible
            imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
            PBarimgUpdateDatabase.Visibility = Windows.Visibility.Hidden
        End Try
    End Sub
#End Region

#Region "Control Events"
    Private Sub btnExtract_Click(ByVal sender As System.Object, ByVal e As System.Windows.RoutedEventArgs) Handles btnExtract.Click
        listboxNotonDatabase.Items.Clear()
        oRapi = New RAPI
        imgDeviceError.Visibility = Windows.Visibility.Hidden

        PBar.Visibility = Windows.Visibility.Visible
        Dim duration As Duration = New Duration(TimeSpan.FromSeconds(20))
        Dim doubleAnimation As Animation.DoubleAnimation = New Animation.DoubleAnimation(200.0, duration)
        PBar.BeginAnimation(ProgressBar.ValueProperty, doubleAnimation)
        PBarimgFilesFound.BeginAnimation(ProgressBar.ValueProperty, doubleAnimation)
        PBarimgUpdateDatabase.BeginAnimation(ProgressBar.ValueProperty, doubleAnimation)


        If IsDeviceConnected() Then
            If oRapi.Connected Then
                imgDeviceOk.Visibility = Windows.Visibility.Visible
                PBar.Visibility = Windows.Visibility.Hidden
                imgDeviceError.Visibility = Windows.Visibility.Hidden
                If FilesFoundOnDevice() Then
                    If remotefileCount > 0 Then
                        imgFilesFoundOk.Visibility = Windows.Visibility.Visible
                        PBarimgFilesFound.Visibility = Windows.Visibility.Hidden
                        imgFilesFoundError.Visibility = Windows.Visibility.Hidden
                        If removeFilesonReader Then
                            removeFilesFromDevice()
                        End If
                    Else
                        imgFilesFoundOk.Visibility = Windows.Visibility.Hidden
                        imgFilesFoundError.Visibility = Windows.Visibility.Visible
                        PBarimgFilesFound.Visibility = Windows.Visibility.Hidden
                    End If
                    PBarimgUpdateDatabase.Visibility = Windows.Visibility.Visible
                    imgUpdateDatabaseError.Visibility = Windows.Visibility.Hidden
                    imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
                    UpdateRFIDData()
                Else
                    imgFilesFoundOk.Visibility = Windows.Visibility.Hidden
                    imgFilesFoundError.Visibility = Windows.Visibility.Visible
                    PBarimgFilesFound.Visibility = Windows.Visibility.Hidden

                    imgUpdateDatabaseError.Visibility = Windows.Visibility.Visible
                    imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
                    PBarimgUpdateDatabase.Visibility = Windows.Visibility.Hidden
                End If

            Else
                imgDeviceOk.Visibility = Windows.Visibility.Hidden
                imgDeviceError.Visibility = Windows.Visibility.Visible
                PBar.Visibility = Windows.Visibility.Hidden

                PBarimgUpdateDatabase.Visibility = Windows.Visibility.Visible
                imgUpdateDatabaseError.Visibility = Windows.Visibility.Hidden
                imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
                UpdateRFIDData()
            End If
        Else
            imgDeviceOk.Visibility = Windows.Visibility.Hidden
            imgDeviceError.Visibility = Windows.Visibility.Visible
            PBar.Visibility = Windows.Visibility.Hidden

            imgFilesFoundOk.Visibility = Windows.Visibility.Hidden
            imgFilesFoundError.Visibility = Windows.Visibility.Visible
            PBarimgFilesFound.Visibility = Windows.Visibility.Hidden

            imgUpdateDatabaseError.Visibility = Windows.Visibility.Visible
            imgUpdateDatabaseOk.Visibility = Windows.Visibility.Hidden
            PBarimgUpdateDatabase.Visibility = Windows.Visibility.Hidden
        End If
        If listboxNotonDatabase.Items.Count > 0 Then
            spNotonDatabase.Visibility = Windows.Visibility.Visible
        End If
    End Sub
#End Region
End Class
